<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\Antiepidemic;
use App\Models\Category;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Show;
use Illuminate\Http\Request;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;

class AntiepidemicController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Antiepidemic(), function (Grid $grid) {
            $grid->column('id')->sortable();
            $grid->column('studentName');
            $grid->column('studentSex')->display(function ($item) {
                return $item == 1 ? '男' : '女';
            });
            $grid->column('school');
            $grid->column('grade');
            $grid->column('parentName');
            $grid->column('phone');
            $grid->column('address');
            $grid->column('created_at')->sortable();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->panel();
                $filter->expand();
                $filter->like('studentName')->width('4');
                $filter->equal('category_id', '分类')->select(Category::query()->pluck('title', 'id'))->width('4');
            });
//            $grid->tools(function ($tools) {
//
//                $tools->append('<a href="export" target="_blank" class="btn btn-primary outline">导出</a>');
//            });

        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Antiepidemic(), function (Show $show) {
            $show->field('id');
            $show->field('studentName');
            $show->field('studentSex')->as(function ($item) {
                return $item == 1 ? '男' : '女';
            });
            $show->field('school');
            $show->field('grade');
            $show->field('parentName');
            $show->field('phone');
            $show->field('address');
            $show->field('healthCodeList')->unescape()->as(function ($item) {
                if ($item) {
                    $str = '<div>';
                    $item = json_decode($item, true);
                    foreach ($item as $v) {
                        $str .= "<a href='" . $v['url'] . "' target='_blank'><img src='" . $v['url'] . "' style='width:64px;height:64px;margin-right:10px;'></a>";
                    }
                    $str .= "</div>";
                    return $str;
                }
            });
            $show->field('tourCodeList')->unescape()->as(function ($item) {
                if ($item) {
                    $str = '<div>';
                    $item = json_decode($item, true);
                    foreach ($item as $v) {
                        $str .= "<a href='" . $v['url'] . "' target='_blank'><img src='" . $v['url'] . "' style='width:64px;height:64px;margin-right:10px;'></a>";
                    }
                    $str .= "</div>";
                    return $str;
                }
            });
            $show->field('identityList')->unescape()->as(function ($item) {
                if ($item) {
                    $str = '<div>';
                    $item = json_decode($item, true);
                    foreach ($item as $v) {
                        $str .= "<a href='" . $v['url'] . "' target='_blank'><img src='" . $v['url'] . "' style='width:64px;height:64px;margin-right:10px;'></a>";
                    }
                    $str .= "</div>";
                    return $str;
                }
            });
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Antiepidemic(), function (Form $form) {
            $form->display('id');
            $form->text('studentName');
            $form->text('studentSex');
            $form->text('school');
            $form->text('grade');
            $form->text('parentName');
            $form->text('phone');
            $form->text('address');
            $form->text('healthCodeList');
            $form->text('tourCodeList');
            $form->text('identityList');

            $form->display('created_at');
            $form->display('updated_at');
        });
    }


    public function export($id, Request $request)
    {
        set_time_limit(0);
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        //设置sheet的名字
        $sheet->setTitle('Hello');
        //设置第一行小标题
        $k = 1;
        $sheet->setCellValue('A' . $k, '学生姓名');
        $sheet->setCellValue('B' . $k, '学生性别');
        $sheet->setCellValue('C' . $k, '学校名称');
        $sheet->setCellValue('D' . $k, '年级');
        $sheet->setCellValue('E' . $k, '家长姓名');
        $sheet->setCellValue('F' . $k, '手机号');
        $sheet->setCellValue('G' . $k, '家庭住址');
        $sheet->setCellValue('H' . $k, '健康码1');
        $sheet->setCellValue('I' . $k, '健康码2');
        $sheet->setCellValue('J' . $k, '行程码1');
        $sheet->setCellValue('K' . $k, '行程码2');
        $sheet->setCellValue('L' . $k, '身份信息1');
        $sheet->setCellValue('M' . $k, '身份信息2');

        $spreadsheet->getActiveSheet()->getColumnDimension('H')->setWidth(20);
        $spreadsheet->getActiveSheet()->getColumnDimension('I')->setWidth(20);
        $spreadsheet->getActiveSheet()->getColumnDimension('J')->setWidth(20);
        $spreadsheet->getActiveSheet()->getColumnDimension('K')->setWidth(20);
        $spreadsheet->getActiveSheet()->getColumnDimension('L')->setWidth(20);
        $spreadsheet->getActiveSheet()->getColumnDimension('M')->setWidth(20);

        //获取最新的分类id

        $data = \App\Models\Antiepidemic::query()->where('category_id', $id)->get()->toArray();
//        dd($data);
        $info = collect($data);
        $k = 2;
        foreach ($info as $key => $value) {
            $sheet->setCellValue('A' . $k, $value['studentName']);
            $sheet->setCellValue('B' . $k, $value['studentSex']);
            $sheet->setCellValue('C' . $k, $value['school']);
            $sheet->setCellValue('D' . $k, $value['grade']);
            $sheet->setCellValue('E' . $k, $value['parentName']);
            $sheet->setCellValue('F' . $k, $value['phone']);
            $sheet->setCellValue('G' . $k, $value['address']);

            if ($value['healthCodeList']) {
                $value['healthCodeList'] = json_decode($value['healthCodeList'], true);
                $img = self::curlGet($value['healthCodeList'][0]['url']);
                $dir = public_path('/uoloads/images/');
                $file_info = pathinfo($value['healthCodeList'][0]['url']);
                if (!empty($file_info['basename'])) { //过滤非文件类型
                    $basename = $file_info['basename'];
                    is_dir($dir) or mkdir($dir, 0777, true); //进行检测文件是否存在
                    file_put_contents($dir . $basename, $img);

                    $drawing[$k] = new Drawing();
                    $drawing[$k]->setName('Logo');
                    $drawing[$k]->setDescription('Logo');
                    $drawing[$k]->setPath($dir . $basename);
                    $drawing[$k]->setWidth(80);
                    $drawing[$k]->setHeight(80);
                    $drawing[$k]->setCoordinates('H' . $k);
                    $drawing[$k]->setOffsetX(12);
                    $drawing[$k]->setOffsetY(12);
                    $drawing[$k]->setWorksheet($spreadsheet->getActiveSheet());
                } else {
                    $sheet->setCellValue('H' . $k, '');
                }
                if (count($value['healthCodeList']) == 2) {
                    $img = self::curlGet($value['healthCodeList'][1]['url']);
                    $dir = public_path('/uoloads/images/');
                    $file_info = pathinfo($value['healthCodeList'][1]['url']);
                    if (!empty($file_info['basename'])) { //过滤非文件类型
                        $basename = $file_info['basename'];
                        is_dir($dir) or mkdir($dir, 0777, true); //进行检测文件是否存在
                        file_put_contents($dir . $basename, $img);

                        $drawing[$k] = new Drawing();
                        $drawing[$k]->setName('Logo');
                        $drawing[$k]->setDescription('Logo');
                        $drawing[$k]->setPath($dir . $basename);
                        $drawing[$k]->setWidth(80);
                        $drawing[$k]->setHeight(80);
                        $drawing[$k]->setCoordinates('I' . $k);
                        $drawing[$k]->setOffsetX(12);
                        $drawing[$k]->setOffsetY(12);
                        $drawing[$k]->setWorksheet($spreadsheet->getActiveSheet());
                    } else {
                        $sheet->setCellValue('I' . $k, '');
                    }
                } else {
                    $sheet->setCellValue('I' . $k, '');
                }

            }
            if ($value['tourCodeList']) {
                $value['tourCodeList'] = json_decode($value['tourCodeList'], true);
                $img = self::curlGet($value['tourCodeList'][0]['url']);
                $dir = public_path('/uoloads/images/');
                $file_info = pathinfo($value['tourCodeList'][0]['url']);
                if (!empty($file_info['basename'])) { //过滤非文件类型
                    $basename = $file_info['basename'];
                    is_dir($dir) or mkdir($dir, 0777, true); //进行检测文件是否存在
                    file_put_contents($dir . $basename, $img);

                    $drawing[$k] = new Drawing();
                    $drawing[$k]->setName('Logo');
                    $drawing[$k]->setDescription('Logo');
                    $drawing[$k]->setPath($dir . $basename);
                    $drawing[$k]->setWidth(80);
                    $drawing[$k]->setHeight(80);
                    $drawing[$k]->setCoordinates('J' . $k);
                    $drawing[$k]->setOffsetX(12);
                    $drawing[$k]->setOffsetY(12);
                    $drawing[$k]->setWorksheet($spreadsheet->getActiveSheet());
                } else {
                    $sheet->setCellValue('J' . $k, '');
                }
                if (count($value['tourCodeList']) == 2) {
                    $img = self::curlGet($value['tourCodeList'][1]['url']);
                    $dir = public_path('/uoloads/images/');
                    $file_info = pathinfo($value['tourCodeList'][1]['url']);
                    if (!empty($file_info['basename'])) { //过滤非文件类型
                        $basename = $file_info['basename'];
                        is_dir($dir) or mkdir($dir, 0777, true); //进行检测文件是否存在
                        file_put_contents($dir . $basename, $img);

                        $drawing[$k] = new Drawing();
                        $drawing[$k]->setName('Logo');
                        $drawing[$k]->setDescription('Logo');
                        $drawing[$k]->setPath($dir . $basename);
                        $drawing[$k]->setWidth(80);
                        $drawing[$k]->setHeight(80);
                        $drawing[$k]->setCoordinates('K' . $k);
                        $drawing[$k]->setOffsetX(12);
                        $drawing[$k]->setOffsetY(12);
                        $drawing[$k]->setWorksheet($spreadsheet->getActiveSheet());
                    } else {
                        $sheet->setCellValue('K' . $k, '');
                    }
                } else {
                    $sheet->setCellValue('K' . $k, '');
                }

            }
            if ($value['identityList']) {
                $value['identityList'] = json_decode($value['identityList'], true);
                $img = self::curlGet($value['identityList'][0]['url']);
                $dir = public_path('/uoloads/images/');
                $file_info = pathinfo($value['identityList'][0]['url']);
                if (!empty($file_info['basename'])) { //过滤非文件类型
                    $basename = $file_info['basename'];
                    is_dir($dir) or mkdir($dir, 0777, true); //进行检测文件是否存在
                    file_put_contents($dir . $basename, $img);

                    $drawing[$k] = new Drawing();
                    $drawing[$k]->setName('Logo');
                    $drawing[$k]->setDescription('Logo');
                    $drawing[$k]->setPath($dir . $basename);
                    $drawing[$k]->setWidth(80);
                    $drawing[$k]->setHeight(80);
                    $drawing[$k]->setCoordinates('L' . $k);
                    $drawing[$k]->setOffsetX(12);
                    $drawing[$k]->setOffsetY(12);
                    $drawing[$k]->setWorksheet($spreadsheet->getActiveSheet());
                } else {
                    $sheet->setCellValue('L' . $k, '');
                }
                if (count($value['identityList']) == 2) {
                    $img = self::curlGet($value['identityList'][1]['url']);
                    $dir = public_path('/uoloads/images/');
                    $file_info = pathinfo($value['identityList'][1]['url']);
                    if (!empty($file_info['basename'])) { //过滤非文件类型
                        $basename = $file_info['basename'];
                        is_dir($dir) or mkdir($dir, 0777, true); //进行检测文件是否存在
                        file_put_contents($dir . $basename, $img);

                        $drawing[$k] = new Drawing();
                        $drawing[$k]->setName('Logo');
                        $drawing[$k]->setDescription('Logo');
                        $drawing[$k]->setPath($dir . $basename);
                        $drawing[$k]->setWidth(80);
                        $drawing[$k]->setHeight(80);
                        $drawing[$k]->setCoordinates('M' . $k);
                        $drawing[$k]->setOffsetX(12);
                        $drawing[$k]->setOffsetY(12);
                        $drawing[$k]->setWorksheet($spreadsheet->getActiveSheet());
                    } else {
                        $sheet->setCellValue('M' . $k, '');
                    }
                } else {
                    $sheet->setCellValue('M' . $k, '');
                }
            }
            $sheet->getRowDimension($k)->setRowHeight(80);
            $k++;
        }

        $file_name = date('Y-m-d', time()) . rand(1000, 9999);
        //  第二种直接页面上显示下载
        $file_name = $file_name . ".xlsx";
        header('Content-Descripyon:File Transfer');
        header('Expires: 0');
        header('Pragma: public');
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $file_name . '"');
        header('Cache-Control: must-revalidate');
        header('Cache-Control: max-age=0');
        $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
//        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
        //  注意createWriter($spreadsheet, 'Xls') 第二个参数首字母必须大写
        $writer->save('php://output');

        $fp = fopen('php://output', 'a'); //打开output流
        mb_convert_variables('GBK', 'UTF-8', $columns);
        fputcsv($fp, $columns);
        $dataNum = count($info);
        $perSize = 1000;//每次导出的条数
        $pages = ceil($dataNum / $perSize);
        for ($i = 1; $i <= $pages; $i++) {
            foreach ($info as $item) {
                mb_convert_variables('GBK', 'UTF-8', $item);
                fputcsv($fp, $item);
            }
            //刷新输出缓冲到浏览器
            ob_flush();
            flush(); // 必须同时使用ob_flush和flush函数来刷新输出缓冲
        }
        fclose($fp);
        exit;
    }

    public function getClient()
    {
        $client = new Client();
        return $client;
    }

    public static function curlGet($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 这个是重点 请求https。
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
}
